<?php

namespace app\common\model\xiluedu;

use app\common\library\Auth;
use app\common\model\User;
use think\Db;
use think\Exception;
use think\Hook;
use think\Model;
use function fast\array_get;


class VipOrder extends Model
{
    // 表名
    protected $name = 'xiluedu_vip_order';

    protected $autoWriteTimestamp = 'int';

    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    public function user() {
        return $this->belongsTo(User::class, 'user_id')->setEagerlyType(0);
    }

    public function vip() {
        return $this->belongsTo('Vip', 'vip_id')->setEagerlyType(0);
    }

    /**
     * 创建订单
     * @param $params
     * @return VipOrder|array
     * @throws Exception
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function createOrder($params) {
        $vip_id = array_get($params,'vip_id');
        if(!$vip_id){
            throw new Exception("非法参数");
        }
        $vip = Vip::get($vip_id);
        if(!$vip || $vip->status == '0'){
            throw new Exception("Vip卡不存在或已下架");
        }
        $platform = array_get($params,'platform','wxmini');
        $auth = Auth::instance();
        #订单创建
        $data = [
            'platform'      =>  $platform,
            'user_id'       =>  $auth->id,
            'order_no'      =>  "V".date("YmdHis").mt_rand(10,9999),
            'total_price'   =>  $vip['salesprice'],
            'pay_price'     =>  $vip['salesprice'],
            'pay_status'    =>  0,
            'vip_id'        =>  $vip_id,
            'vip_name'      =>  $vip['name'],
            'vip_salesprice'=>  $vip['salesprice'],
            'vip_expire'    =>  $vip['expire_in'],
            'vip_unit'      =>  $vip['unit'],
            'ip'            =>  request()->ip(),
        ];
        $result = self::create($data);
        if($result !== false){
            Hook::listen("xiluedu_order_divide",$result,['type'=>'vip']);
            return $result;
        }else {
            throw new Exception("订单创建失败");
        }
    }

    public static function pay_notify($order_no){
        $order = self::where('order_trade_no',$order_no)->find();
        if(!$order){
            throw new Exception('订单不存在');
        }
        if($order->pay_status == '1'){
            throw new Exception('订单已支付完毕');
        }
        #更新订单状态
        $order->pay_status = '1';
        $order->paytime = time();
        $order->save();
        #分销佣金更新为已支付、待分配
        if($divide = OrderDivide::checkExist($order->id,'vip')){
            $divide->save(['status'=>2]);
        }
        #更新会员卡时间
        $user_vip = UserVip::where('user_id',$order->user_id)->find();
        if($order->vip_unit == '3'){
            $unit = 'year';
        }else if($order->vip_unit == '2'){
            $unit = 'month';
        }else{
            $unit = 'day';
        }
        $time = date('Y-m-d');
        if(!$user_vip || ($user_vip['expire_time'] < strtotime($time))){
            $expire_time = strtotime(date('Y-m-d',strtotime($order->vip_expire.' '.$unit)));
        }else{
            $expire_time = strtotime("+".$order->vip_expire." ".$unit." ".date('Y-m-d',$user_vip['expire_time']));
        }
        $user_vip_ret = [
            'user_id'   =>  $order->user_id,
            'vip_id'    =>  $order->vip_id,
            'expire_time'=> $expire_time
        ];
        if(!$user_vip){
            UserVip::create($user_vip_ret);
        }else{
            $user_vip->save($user_vip_ret);
        }
        Hook::listen("xiluedu_vip_buy",$order);
        Hook::listen("xiluedu_divide",$order,['type'=>'vip']);
        return $order;
    }

}
